<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * @author petra.barus
 */
class Compiler {

    public static function compile($sourcepath, $sourcelang, &$outputpath = NULL, $parameter = NULL)
    {
        $compiletimelimit = 1;
        $compilememorylimit = 32000;
        $parameter = (!is_null($parameter) && isset($parameter[$sourcelang])) ? $parameter[$sourcelang] : '';
        if (is_null($outputpath))
        {
            $outputpath = Sandbox::get_temp_name();
        }
        $compiler_gcc_path = Kohana::config('evaluator.compiler_gcc_path');
        $compiler_cpp_path = Kohana::config('evaluator.compiler_cpp_path');
        $compiler_fpc_path = Kohana::config('evaluator.compiler_fpc_path');
        //

        switch($sourcelang)
        {
            case 'pascal' :
                $compilecmd = "$compiler_fpc_path $parameter -o$outputpath $sourcepath";
                break;
            case 'c' :
                $compilecmd = "$compiler_cpp_path -x c -std=c99 $parameter -o $outputpath $sourcepath";
                break;
            case 'c++' :
                $compilecmd = "$compiler_gcc_path -x c++ -std=c99 $parameter -o $outputpath $sourcepath";
                break;
            default :
                echo " Error in grading: Source language not recognized";
                throw new CompilerException(CompilerException::ERR_LANGUAGE_UNRECOGNIZED);
                break;
        }
        $sandboxparam = "-e -m $compilememorylimit -w $compiletimelimit";
        $sandboxexec = $compilecmd;
        $sandboxoutput = "";
        $retval = 0;
        try
        {
            Sandbox::execute($sandboxparam, $sandboxexec, &$sandboxoutput, &$retval);
        }
        catch (SandboxException $ex)
        {
            throw new CompilerException(CompilerException::ERR_COMPILE_ERROR);
        }
        if ($retval != 0)
        {
            throw new CompilerException(CompilerException::ERR_COMPILE_ERROR);
        }
        if ($sourcelang == 'pascal')
        {
            unlink($sourcepath.".o");
        }
        return $outputpath;
    }
}
//end of file